<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Widgets\TxtBox;
use App\Http\Controllers\Controller;
use App\Models\Admin\Pinion;
use App\Models\Member\User;
use App\Models\Order\Info;
use App\Models\Sys\Exchange;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\InfoBox;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        //统计数据
        //今日数据
        $today_start = strtotime(date('Y-m-d 00:00:00', time()));
        $today_end = time();
        $today_data = Info::where('pay_time', '>=', $today_start)
            ->where('pay_time', '<=', $today_end)
            ->where('pay_status', 2)
            ->select([DB::raw('COUNT(*) count'),DB::raw('SUM(total_fee) total_fee')])
            ->first()->toArray();

        if ($today_data){
            $today_data['total_fee'] = $today_data['total_fee'] ? $today_data['total_fee'] : 0;
        }
        //昨日
        $yesterday_start = strtotime(date('Y-m-d 00:00:00',strtotime('-1 day')));
        $yesterday_end = strtotime(date('Y-m-d 23:59:59',strtotime('-1 day')));
        $yesterday_data = Info::where('pay_time', '>=', $yesterday_start)
            ->where('pay_time', '<=', $yesterday_end)
            ->where('pay_status', 2)
            ->sum('total_fee');

        //近7日
        $seven_start = strtotime(date('Y-m-d 00:00:00',strtotime('-7 day')));
        $seven_end = time();
        $seven_data = Info::where('pay_time', '>=', $seven_start)
            ->where('pay_time', '<=', $seven_end)
            ->where('pay_status', 2)
            ->sum('total_fee');

        $total_data = compact('today_data','yesterday_data','seven_data');


        //待处理事务 is_delivery是否发货 1是 2否
        $exchange_data = Exchange::whereIn('is_delivery',[1,2])
        ->select([
            DB::raw('SUM(CASE WHEN is_delivery = 2 THEN 1 ELSE 0 END) delivering_count'),
            DB::raw('SUM(CASE WHEN is_delivery = 1 THEN 1 ELSE 0 END) delivered_count')
        ])
        ->first()->toArray();

        //老师vip即将到期 expiry_time 到期时间 一个月内到期的
        $month_date = strtotime('+1 month');
        $vip_count = User::where('expiry_time','<=',$month_date)
            ->where('expiry_time','>',time())
            ->count();

        //家长订阅即将到期 1个月内即将到期的
        $month_after = strtotime(date('Y-m-d H:i:s',strtotime('+1 month')));
        $subscribe_count = \App\Models\Subscribe\Info::where('end_time','>',$today_end)
            ->where('end_time','<',$month_after)
            ->where('status','1')
            ->count();

        $msg_count = Pinion::count();

        //待处理事务 数据汇总
        $pending_transaction = [
            'delivering_count' => $exchange_data['delivering_count'],//待发货
            'delivered_count'  => $exchange_data['delivered_count'],//已发货
            'vip_count'        => $vip_count,//vip即将到期数
            'shortage_count'   => '未知',//新缺货登记
            'subscribe_count'  => $subscribe_count,//家长订阅即将到期
            'msg_count'        => $msg_count,//客户留言
        ];

        $curr_month_start = strtotime(date("Y-m-01 00:00:00",time()));
        $curr_month_end = strtotime(date("Y-m-01 23:59:59", time()) . "+1 month -1 day");

        //订阅总览
        $subscribe_total = \App\Models\Subscribe\Info::where('end_time','>',$today_end)
            ->where('status','1')
            ->select([
                DB::raw("SUM(CASE WHEN subscribe_time > $today_start AND subscribe_time < $today_end THEN 1 ELSE 0 END) today_count"),
                DB::raw("SUM(CASE WHEN subscribe_time > $yesterday_start AND subscribe_time < $yesterday_end THEN 1 ELSE 0 END) yesterday_count"),
                DB::raw("SUM(CASE WHEN subscribe_time > $curr_month_start AND subscribe_time < $today_end THEN 1 ELSE 0 END) curr_month_count"),
                DB::raw("COUNT(*) total_count")
            ])->first()->toArray();

        $subscribe_data = [
            [
                'name' => '今日新增',
                'txt'  => $subscribe_total['today_count'],
                'link' => ''
            ],
            [
                'name' => '昨日新增',
                'txt'  => $subscribe_total['yesterday_count'],
                'link' => ''
            ],
            [
                'name' => '本月新增',
                'txt'  => $subscribe_total['curr_month_count'],
                'link' => ''
            ],
            [
                'name' => '订阅总数',
                'txt'  => $subscribe_total['total_count'],
                'link' => ''
            ],
        ];

        //老师vip总览
        $vip_total = User::where('expiry_time','>',time())
            ->select([
                DB::raw("SUM(CASE WHEN start_time > $today_start AND start_time < $today_end THEN 1 ELSE 0 END) today_count"),
                DB::raw("SUM(CASE WHEN start_time > $yesterday_start AND start_time < $yesterday_end THEN 1 ELSE 0 END) yesterday_count"),
                DB::raw("SUM(CASE WHEN start_time > $curr_month_start AND start_time < $today_end THEN 1 ELSE 0 END) curr_month_count"),
                DB::raw("COUNT(*) total_count")
            ])->first()->toArray();
        $vip_data = [
            [
                'name' => '今日新增',
                'txt'  => $vip_total['today_count'],
                'link' => ''
            ],
            [
                'name' => '昨日新增',
                'txt'  => $vip_total['yesterday_count'],
                'link' => ''
            ],
            [
                'name' => '本月新增',
                'txt'  => $vip_total['curr_month_count'],
                'link' => ''
            ],
            [
                'name' => '会员总数',
                'txt'  => $vip_total['total_count'],
                'link' => ''
            ],
        ];

        //----订单统计 S----
        //上月开始点
        $last_month_start = strtotime(date("Y-m-01 00:00:00",strtotime('-1 month')));
        //上月结束点
        $last_month_end = $curr_month_start - 1;
        //本周开始点
        $curr_week_start = strtotime(date('Y-m-d 00:00:00', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)));
        //上周开始点
        $last_week_start = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
        //上周结束点
        $last_week_end = $curr_week_start - 1;

        //获取订单数据
        $order_data = Info::where('pay_status','2')
            ->select([
                DB::raw("SUM(CASE WHEN pay_time >= $curr_month_start AND pay_time <= $today_end THEN 1 ELSE 0 END) curr_month_count"),
                DB::raw("SUM(CASE WHEN pay_time >= $last_month_start AND pay_time <= $last_month_end THEN 1 ELSE 0 END) last_month_count"),
                DB::raw("SUM(CASE WHEN pay_time >= $curr_week_start AND pay_time <= $today_end THEN 1 ELSE 0 END) curr_week_count"),
                DB::raw("SUM(CASE WHEN pay_time >= $last_week_start AND pay_time <= $last_week_end THEN 1 ELSE 0 END) last_week_count"),
            ])
            ->first()->toArray();

        //计算本月/上月同比
        $month_offset = $order_data['curr_month_count'] - $order_data['last_month_count'];
        if ($month_offset < 0){
            $order_data['month_type'] = 'caret-down';
            $order_data['month_rate'] = number_format(abs($month_offset) * 100 / $order_data['last_month_count'], 2, '.','');
        } else if ($month_offset > 0 && $order_data['last_month_count'] > 0){
            $order_data['month_type'] = 'caret-up';
            $order_data['month_rate'] = number_format($month_offset * 100 / $order_data['last_month_count'], 2, '.','');
        } else {
            $order_data['month_type'] = 'minus';
            $order_data['month_rate'] = '0';
        }
        //计算本周/上周同比
        $week_offset = $order_data['curr_week_count'] - $order_data['last_week_count'];
        if ($week_offset < 0){
            $order_data['week_type'] = 'caret-down';
            $order_data['week_rate'] = number_format(abs($week_offset) * 100 / $order_data['last_week_count'], 2, '.','');
        } else if ($week_offset > 0 && $order_data['last_week_count'] > 0){
            $order_data['week_type'] = 'caret-up';
            $order_data['week_rate'] = number_format($week_offset * 100 / $order_data['last_week_count'], 2, '.','');
        } else {
            $order_data['week_type'] = 'minus';
            $order_data['week_rate'] = '0';
        }

        //获取兑换统计数据
        $exchange_data = Exchange::select([
                DB::raw("SUM(CASE WHEN create_at >= $curr_month_start AND create_at <= $today_end THEN money ELSE 0 END) curr_month_count"),
                DB::raw("SUM(CASE WHEN create_at >= $last_month_start AND create_at <= $last_month_end THEN money ELSE 0 END) last_month_count"),
                DB::raw("SUM(CASE WHEN create_at >= $curr_week_start AND create_at <= $today_end THEN money ELSE 0 END) curr_week_count"),
                DB::raw("SUM(CASE WHEN create_at >= $last_week_start AND create_at <= $last_week_end THEN money ELSE 0 END) last_week_count"),
            ])->first()->toArray();
        //计算本月/上月同比
        $month_offset = $exchange_data['curr_month_count'] - $exchange_data['last_month_count'];
        if ($month_offset < 0){
            $exchange_data['month_type'] = 'caret-down';
            $exchange_data['month_rate'] = number_format(abs($month_offset) * 100 / $exchange_data['last_month_count'], 2, '.','');
        } else if ($month_offset > 0 && $exchange_data['last_month_count'] > 0){
            $exchange_data['month_type'] = 'caret-up';
            $exchange_data['month_rate'] = number_format($month_offset * 100 / $exchange_data['last_month_count'], 2, '.','');
        } else {
            $exchange_data['month_type'] = 'minus';
            $exchange_data['month_rate'] = '0';
        }
        //计算本周/上周同比
        $week_offset = $exchange_data['curr_week_count'] - $exchange_data['last_week_count'];
        if ($week_offset < 0){
            $exchange_data['week_type'] = 'caret-down';
            $exchange_data['week_rate'] = number_format(abs($week_offset) * 100 / $exchange_data['last_week_count'], 2, '.','');
        } else if ($week_offset > 0 && $exchange_data['last_week_count'] > 0){
            $exchange_data['week_type'] = 'caret-up';
            $exchange_data['week_rate'] = number_format($week_offset * 100 / $exchange_data['last_week_count'], 2, '.','');
        } else {
            $exchange_data['week_type'] = 'minus';
            $exchange_data['week_rate'] = '0%';
        }

        //----订单统计 E----


        return $content
            ->header('系统首页')
            ->description('Description...')
            ->row(function (Row $row) use ($total_data) {
                $row->column(3, new InfoBox('今日订单总数', 'file-text', 'aqua', '#', $total_data['today_data']['count']));
                $row->column(3, new InfoBox('今日销售总额', 'jpy', 'green', '#', $total_data['today_data']['total_fee']));
                $row->column(3, new InfoBox('昨日销售总额', 'pie-chart', 'yellow', '#', $total_data['yesterday_data']));
                $row->column(3, new InfoBox('近7天销售总额', 'bar-chart', 'red', '#', $total_data['seven_data']));
            })
            ->row(new Box('待处理事务', view('admin.index.pending-transaction',['data' => $pending_transaction])))
            ->row(new Box('运营快捷入口', view('admin.index.shortcut-entry')))
            ->row(function (Row $row) use ($subscribe_data, $vip_data){

                $row->column(6, (new TxtBox('订阅总览', $subscribe_data))->style('txt-box'));

                $row->column(6, (new TxtBox('老师vip总览', $vip_data))->style('txt-box'));
            })
            ->row(view('admin.index.order',compact('order_data', 'exchange_data')));
    }

    public function getOrderData(Request $request)
    {
        $days_type = $request->get('days_type', 2);//1今天 2本周(默认) 3本月 0自定义
        $start_time = $request->get('start_time');
        $end_time   = $request->get('end_time');

        $type_data = $this->getType($days_type, $start_time, $end_time);
        if ($type_data){
            $start_time = $type_data['start_time'];
            $end_time = $type_data['end_time'];
            $title = $type_data['title'];
            $group_type = $type_data['group_type'];
        } else {
            return [];
        }

        $row = Info::where('pay_time', '>=', $start_time)
            ->where('pay_time', '<=', $end_time)
            ->where('pay_status', '2')
            ->get()->toArray();

        $data = [];
        switch ($group_type){
            case 1:
                foreach ($row as $key=>$val){
                    $date = date('Y-m-d H', $val['pay_time']);
                    if (!isset($data[$date])){
                        $data[$date] = 0;
                    }
                    $data[$date] += 1;
                }
                break;
            case 2:
                foreach ($row as $key=>$val){
                    $date = date('Y-m-d', $val['pay_time']);
                    if (!isset($data[$date])){
                        $data[$date] = 0;
                    }
                    $data[$date] += 1;
                }
                break;
            case 3:
                foreach ($row as $key=>$val){
                    $date = date('Y-m', $val['pay_time']);
                    if (!isset($data[$date])){
                        $data[$date] = 0;
                    }
                    $data[$date] += 1;
                }
                break;
        }

        $d['title'] = $title;
        foreach ($data as $key=>$val){
            $d['xAxis'][] = $key;
            $d['series'][] = $val . '';
        }

        return response()->json($d);
    }

    public function getExchangeData(Request $request)
    {
        $days_type = $request->get('days_type', 2);//1今天 2本周(默认) 3本月 0自定义
        $start_time = $request->get('start_time');
        $end_time   = $request->get('end_time');

        $type_data = $this->getType($days_type, $start_time, $end_time);
        if ($type_data){
            $start_time = $type_data['start_time'];
            $end_time = $type_data['end_time'];
            $title = $type_data['title'];
            $group_type = $type_data['group_type'];
        } else {
            return [];
        }

        $row = Exchange::where('create_at', '>=', $start_time)
            ->where('create_at', '<=', $end_time)
            ->get()->toArray();

        $data = [];
        switch ($group_type){
            case 1:
                foreach ($row as $key=>$val){
                    $date = date('Y-m-d H', strtotime($val['create_at']));
                    if (!isset($data[$date])){
                        $data[$date] = 0;
                    }
                    $data[$date] += $val['money'];
                }
                break;
            case 2:
                foreach ($row as $key=>$val){
                    $date = date('Y-m-d', strtotime($val['create_at']));
                    if (!isset($data[$date])){
                        $data[$date] = 0;
                    }
                    $data[$date] += $val['money'];
                }
                break;
            case 3:
                foreach ($row as $key=>$val){
                    $date = date('Y-m-d', strtotime($val['create_at']));
                    if (!isset($data[$date])){
                        $data[$date] = 0;
                    }
                    $data[$date] += $val['money'];
                }
                break;
        }

        $d['title'] = $title;
        foreach ($data as $key=>$val){
            $d['xAxis'][] = $key;
            $d['series'][] = $val . '';
        }

        return response()->json($d);
    }

    public function getType($days_type, $start_time, $end_time)
    {
        switch ($days_type){
            case '1':
                //今天 今日0点 至 当前时间
                $start_time = strtotime(date('Y-m-d 00:00:00', time()));
                $end_time = time();
                $title = '今日';
                $group_type = 1;
                break;
            case '2':
                //本周 周一0点 至 当 当前时间
                $start_time = strtotime(date('Y-m-d 00:00:00', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)));
                $end_time   = time();
                $title = '本周';
                $group_type = 2;
                break;
            case '3':
                //本月 本月1号00:00:00 至 当前时间
                $start_time = strtotime(date("Y-m-01 00:00:00",time()));
                $end_time   = time();
                $title = '本月';
                $group_type = 3;
                break;
            default :
                //自定义时间 如果没设置默认今天
                $start_time = isset($start_time) && $start_time ? strtotime($start_time) : strtotime(date('Y-m-d 00:00:00', time()));
                $end_time   = isset($end_time) && $end_time ? strtotime($end_time) : time();

                $title = date('Y-m-d',$start_time) . '至' . date('Y-m-d',$end_time);
                $offset = ($end_time - $start_time) / 86400;
                if ($offset > 0 and $offset <= 1){
                    //按小时分组
                    $group_type = 1;
                } else if ($offset > 1 and $offset <= 31) {
                    //按天分组
                    $group_type = 2;
                } else if ($offset > 31){
                    //按月分组
                    $group_type = 3;
                } else {
                    return [];
                }
                break;
        }

        return [
            'start_time' => $start_time,
            'end_time'   => $end_time,
            'title'      => $title,
            'group_type' => $group_type,
        ];
    }

    /**
     * 上传图片
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function uploadImages(Content $content,Request $request)
    {
        if ($request->ajax()) {
            $file = $request->file('image');

            // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
            $path = $file->store('images', 'qiniu');
            return response()->json(array('msg' => $path));
        }

        return $content
            ->header('系统首页')
            ->description('Description...')
            ->row(view('admin.upload-images'));

    }


}

